
import {getUserInfo, login, logout} from "@/api/login"
import { DRAG_TOKEN} from "@/store/mutation-types"
import  cookies from "vue-cookies"
const user = {
  state: {
    token: '',
    name: '',
    info: null,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state,  name ) => {
      state.name = name
    },
    SET_USER_INFO: (state, user) => {
      state.info = user
    }
  },

  actions: {
    // 登录
    Login({ commit }, data) {
      return new Promise((resolve, reject) => {
        login(data).then((response) =>{
          this.loading = false;
          if(response.data.code ===0){
            const result = response.data
            cookies.set(DRAG_TOKEN,result.data.token)
            commit('SET_TOKEN',result.data.token)
            commit('SET_NAME', result.data.name)
            commit('SET_USER_INFO', result.data)
            resolve(response)
          }else {
            reject(response)
          }

        }).catch(error => {
          reject(error)
        })
      })
    },
    //获取用户信息
    GetUserInfo({ commit }){
      return new Promise((resolve, reject) => {
        getUserInfo().then(response => {
          if(response.data.code === 0){
            const result = response.data
            commit('SET_NAME', result.data.name)
            commit('SET_USER_INFO', result.data)
            resolve(response)
          }else{
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    Logout({commit}){
      return new Promise((resolve, reject) => {
        logout().then(response => {
          if(response.data.code === 0){
            cookies.set(DRAG_TOKEN,'')
            commit('SET_TOKEN', '')
            commit('SET_NAME', '')
            commit('SET_USER_INFO', null)
            resolve(response)
          }else{
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
